const fs = require('fs')

const path = require('path')

//定义正则
const regStyle = /<style>[\s\S]*<\/style>/
const regScript = /<script>[\s\S]*<\/script>/

// 调用 fs.readFile() 方法
fs.readFile(path.join(__dirname, './demoall.html'), 'utf8', (err, data) => {
    if (err) {
        console.log('读取html文件失败' + err.message);
    } else {
        // 调用方法
        resolveCSS(data)
        resolveJS(data)
        resolveHTML(data)
    }
})

function resolveCSS(htmlStr) {
    const r1 = regStyle.exec(htmlStr)
    // 将提取出来的字符串，进行字符串的 replace 替换操作
    const newCSS = r1[0].replace('<style>', '').replace('</style>', '')
    console.log(newCSS);
    // 将提取的样式写入css文件中
    fs.writeFile(path.join(__dirname,'./demo.css'), newCSS, 'utf8', (err) => {
        if (!err) {
            console.log('CSS写入成功！');
        } else {
            console.log('CSS写入失败！' + err.message);
        }
    })
}

function resolveHTML(htmlStr) {
    const newHTML = htmlStr.replace(regStyle,'<link rel="stylesheet" href="./demo.css">').replace(regScript,'<script src="./demo.js"></script>')
    fs.writeFile(path.join(__dirname,'./demo.html'),newHTML,'utf8',(err)=>{
        if(!err){
            console.log('写入html成功');
        }else{
            console.log('写入html失败');
        }
    })
}

function resolveJS(htmlStr) {
    const r1 = regScript.exec(htmlStr)
    const newJS = r1[0].replace('<script>', '').replace('</script>', '')
    fs.writeFile(path.join(__dirname,'./demo.js'), newJS, 'utf8', (err) => {
        if (!err) {
            console.log('JS写入成功！');
        } else {
            console.log('JS写入失败！' + err.message);
        }
    })
}